<template>
  <div class="vue-box" style="display: none;" :style="'display: block;'">
    <el-dialog v-bind="$attrs"
               :visible.sync="dialogVisible"
               :append-to-body="true"
               :close-on-click-modal="false"
               v-on="$listeners" @open="onOpen" @close="onClose" :title="dialogTitle">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules" size="small" label-width="100px">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入角色名称" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="编码" prop="code">
              <el-input v-model="formData.code" placeholder="请输入角色编码" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status" required>
              <el-switch v-model="formData.status" active-text="启用" inactive-text="禁用"
                         inactive-color="#F14D4D"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注或描述" prop="info">
              <el-input v-model="formData.info" type="text" placeholder="请输入备注或描述"
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog v-bind="$attrs"
               :visible.sync="dialogUserVisible"
               :append-to-body="true"
               width="60%"
               :close-on-click-modal="false"
               @open="userOpen"
               v-on="$listeners" :title="'编辑 '+common.roleName+' 角色拥有的用户'">
      <div>
        <el-transfer
            filterable
            @change="transferChange"
            :filter-method="filterMethod"
            :titles="['无此角色用户','有此角色用户']"
            :button-texts="['移除','增加']"
            filter-placeholder="请输入用户姓名"
            v-model="value"
            :data="transferData">
        </el-transfer>
      </div>
    </el-dialog>
    <div class="c-panel">
      <!-- ------------- 检索参数 ------------- -->
      <div class="c-title">角色管理</div>
      <!-- ------------- 快捷按钮 ------------- -->
      <el-row :gutter="15">
        <el-col :span="8">
          <div style="text-align: start;padding: 4px">
            <el-button-group>
              <el-button size="mini" type="success" v-show="!expandAll" @click="setAllExpand">展开</el-button>
              <el-button size="mini" type="info" v-show="expandAll" @click="setAllFold">收起</el-button>
              <el-button size="mini" type="primary" @click="selectAll">全选</el-button>
              <el-button size="mini" type="danger" @click="resetChecked">清空</el-button>
              <el-button size="mini" type="info" @click="reset">重置</el-button>
            </el-button-group>
          </div>
          <div style="text-align: center;padding: 4px">
            <el-popover
                placement="right"
                width="400"
                @show="show(common.id)"
                :open-delay="200"
                :close-delay="200"
                trigger="hover">
              <el-descriptions title="角色信息" size="medium">
                <el-descriptions-item label="名称">{{ showData.name }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                  <el-tag v-if="showData.status">启用</el-tag>
                  <el-tag type="danger" v-else>禁用</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="备注">{{ showData.info }}</el-descriptions-item>
              </el-descriptions>
              <el-tag slot="reference" v-show="common.roleName"> 角色名：{{ common.roleName }}</el-tag>
            </el-popover>
            <el-tag v-show="!common.roleName">点击或勾选角色信息</el-tag>
          </div>
          <div style="text-align: center;padding: 4px">
            <el-button type="primary"
                       :disabled="!common.roleName"
                       @click="saveRoleMenu">
              保存角色菜单
            </el-button>
          </div>
          <div style="height: calc(100vh - var(--nav-right-1-height) - var(--nav-right-2-height) - 40px);
          overflow: auto">
            <el-tree
                ref="menuData"
                :data="menuData"
                show-checkbox
                :default-expand-all="expandAll"
                node-key="id"
                ref="menuTree"
                highlight-current
                :props="defaultProps">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span v-if="data.isShow">{{ node.label }}</span>
              <span v-else style="color: #999;">{{ data.label }}--(隐藏)</span>
              <span>
                <el-popover
                    placement="left"
                    width="200"
                    @show="showMenu(data.id)"
                    :open-delay="200"
                    :close-delay="200"
                    trigger="hover">
                  <el-descriptions title="菜单信息" size="medium" :column="1">
                      <el-descriptions-item label="名称"><i
                          :class="showMenuData.icon"></i>{{ showMenuData.name }}</el-descriptions-item>
                      <el-descriptions-item label="菜单地址">{{ showMenuData.url }}</el-descriptions-item>
                      <el-descriptions-item label="权限编码">{{ showMenuData.permission }}</el-descriptions-item>
                      <el-descriptions-item label="类型">
                        <el-tag v-if="showMenuData.type === 1">菜单</el-tag>
                        <el-tag v-if="showMenuData.type === 2">按钮</el-tag>
                      </el-descriptions-item>
                      <el-descriptions-item label="显示顺序">{{ showMenuData.sort }}</el-descriptions-item>
                    <el-descriptions-item label="是否外链">
                        <el-tag v-if="showMenuData.isBlank">是外链</el-tag>
                        <el-tag v-else>非外链</el-tag>
                      </el-descriptions-item>
                    <el-descriptions-item label="状态">
                        <el-tag v-if="showMenuData.isShow">显示</el-tag>
                        <el-tag v-else>隐藏</el-tag>
                      </el-descriptions-item>
                      <el-descriptions-item label="备注">{{ showMenuData.info }}</el-descriptions-item>
                  </el-descriptions>
                 <el-button type="text" size="mini" slot="reference" @click.stop="">详情</el-button>
                </el-popover>
              </span>
          </span>
            </el-tree>
          </div>
        </el-col>
        <el-col :span="8">
          <el-form :inline="true" @submit.native.prevent>
            <el-button type="primary"
                       @click="dialogTitle='新增角色';dialogVisible=true">
              新增
            </el-button>
            <el-input
                placeholder="输入关键字进行过滤"
                v-model="rolePage.name"
                clearable>
            </el-input>
            <el-button type="danger"
                       @click="delAll">
              删除
            </el-button>
          </el-form>
          <el-table
              ref="roleTable"
              :data="roleData"
              style="width: 100%"
              highlight-current-row
              @select="selectionChange"
              @current-change="currentChange"
              max-height="450">
            <el-table-column type="selection" width="40" align="center"></el-table-column>
            <el-table-column
                prop="name"
                min-width="60"
                label="角色名">
            </el-table-column>
            <el-table-column
                prop="code"
                min-width="60"
                label="编码">
            </el-table-column>
            <el-table-column
                min-width="60"
                label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.status" style="color: green">启用</span>
                <span v-else style="color: red">禁用</span>
              </template>
            </el-table-column>
            <el-table-column
                fixed="right"
                min-width="80"
                label="操作">
              <template slot-scope="scope">
                <el-popover
                    placement="left"
                    width="400"
                    @show="show(scope.row.id)"
                    :open-delay="200"
                    :close-delay="200"
                    trigger="hover">
                  <el-descriptions title="角色信息" size="medium">
                    <el-descriptions-item label="名称">{{ showData.name }}</el-descriptions-item>
                    <el-descriptions-item label="编码">{{ showData.code }}</el-descriptions-item>
                    <el-descriptions-item label="状态">
                      <el-tag v-if="showData.status">启用</el-tag>
                      <el-tag type="danger" v-else>禁用</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="备注">{{ showData.info }}</el-descriptions-item>
                  </el-descriptions>
                  <el-button slot="reference" type="text">查看</el-button>
                </el-popover>

                <el-button
                    @click.native.prevent="edit(scope.row.id)"
                    type="text">
                  编辑
                </el-button>
                <el-popconfirm
                    title="确认移除角色？移除后仅拥有此角色的用户将无法登录！！"
                    @confirm="deleteRow(scope.row.id)"
                >
                  <el-button
                      slot="reference"
                      type="text">
                    移除
                  </el-button>
                </el-popconfirm>

              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              small
              :current-page.sync="rolePage.current"
              :page-size.sync="rolePage.size"
              :total="rolePage.total"
              @current-change="f5()"
              layout="prev, pager, next,total">
          </el-pagination>
        </el-col>
        <el-col :span="8">
          <el-form :inline="true" @submit.native.prevent>
            <el-button type="primary" :disabled="!common.roleName"
                       @click="dialogUserVisible=true">
              编辑
            </el-button>
          </el-form>
          <div style="text-align: center;padding: 4px">
            <el-tag v-if="common.roleName"> 角色名：{{ common.roleName }}</el-tag>
            <el-tag v-if="!common.roleName">点击或勾选角色信息</el-tag>
          </div>
          <el-table
              ref="userData"
              :data="userData"
              style="width: 100%"
              max-height="450">
            <el-table-column type="selection" width="40" align="center"></el-table-column>
            <el-table-column
                prop="name"
                min-width="100"
                label="用户名称">
            </el-table-column>
            <el-table-column
                prop="loginNo"
                min-width="100"
                label="登陆账号">
            </el-table-column>
            <el-table-column
                fixed="right"
                width="60"
                label="操作">
              <template slot-scope="scope">
                <el-popover
                    placement="left"
                    width="600"
                    @show="showUser(scope.row.id)"
                    :open-delay="200"
                    :close-delay="200"
                    trigger="hover">
                  <el-descriptions title="用户信息" size="medium">
                    <el-descriptions-item label="名称">{{ showUserData.name }}</el-descriptions-item>
                    <el-descriptions-item label="手机号">{{ showUserData.phone }}</el-descriptions-item>
                    <el-descriptions-item label="登陆账号">{{ showUserData.loginNo }}</el-descriptions-item>
                    <el-descriptions-item label="用户角色">
                      <el-tag v-for="item in showUserData.roleList" :key="item.id">{{ item.name }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="性别">
                      <el-tag v-if="showUserData.sex === 0 ">男</el-tag>
                      <el-tag type="success" v-if="showUserData.sex === 1 ">女</el-tag>
                      <el-tag type="danger" v-if="showUserData.sex === 2 ">未知</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="用户类型">
                      <el-tag>{{ showUserData.typeName }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="状态">
                      <el-tag v-if="showUserData.status">正常</el-tag>
                      <el-tag type="danger" v-else>锁定</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="最后登陆时间">{{ showUserData.loginEndTime }}</el-descriptions-item>
                    <el-descriptions-item label="备注">{{ showUserData.remark }}</el-descriptions-item>
                  </el-descriptions>
                  <el-button slot="reference" type="text">查看</el-button>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              small
              :current-page.sync="userPage.current"
              :page-size.sync="userPage.size"
              :total="userPage.total"
              @current-change="userF5"
              layout="prev, pager, next,total">
          </el-pagination>
        </el-col>
      </el-row>

    </div>
  </div>
</template>

<script>
let PATH = "/role"
let expandTag = "role"
module.exports = {
  components: {
    "sa-item": httpVueLoader('../../sa-frame/com/sa-item.vue'),
  },
  watch: {
    'rolePage.name': function () {
      this.f5()
    }
  },
  data() {
    return {
      expandAll: sa.getItem(expandTag),
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      common: {
        id: '',
        roleName: ''
      },
      showMenuData: {
        id: '',
        pid: '0',
        type: 1,
        name: undefined,
        icon: undefined,
        url: undefined,
        permission: undefined,
        sort: 0,
        isShow: true,
        isBlank: false,
        info: undefined,
      },
      showUserData: {
        id: undefined,
        name: undefined,
        loginNo: '',
        phone: undefined,
        userType: 'SYS',
        sex: 0,
        status: true,
        roleIds: [],
        remark: undefined,
        loginEndTime: '',
        roleList: [],
        permissionList: []
      },
      roleData: [],
      menuData: [],
      userData: [],
      formData: {
        id: '',
        name: undefined,
        code: undefined,
        status: true,
        info: undefined,
      },
      transferData: [],
      value: [],
      showData: {
        id: '',
        name: undefined,
        code: undefined,
        status: true,
        info: undefined,
      },
      rolePage: {
        // 搜索条件
        name: '',
        current: 1,
        size: 10,
        total: 0
      },
      userPage: {
        // 搜索条件
        id: '',
        current: 1,
        size: 10,
        total: 0
      },
      rules: {
        name: [{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        }],
        code: [{
          required: true,
          message: '请输入角色编码',
          trigger: 'blur'
        }],
        info: [],
      },
      dialogVisible: false,
      dialogUserVisible: false,
      dialogTitle: ''
    }
  },
  methods: {
    transferChange(val) {
      sa.ajax(PATH + "/change-role-user", {id: this.common.id, userIds: JSON.stringify(val)}, (res) => {
        sa.msgOk(res.msg, () => {
          this.userF5()
        })
      }, {msg: null})
    },
    filterMethod(query, item) {
      return item.label.indexOf(query) > -1;
    },
    userF5() {
      this.userPage.id = this.common.id;
      sa.ajax(PATH + "/user-list-by-role-id", this.userPage, (res) => {
        this.userData = res.data
        this.userPage.total = res.dataCount
      }, {type: 'get', msg: null})
    },
    selectAll() { // 全选
      let tree = this.$refs['menuData'];
      tree.setCheckedKeys(this.menuData.map((i) => i.id));
    },
    saveRoleMenu() { // 保存角色信息
      let tree = this.$refs['menuData'];
      sa.ajax(PATH + "/sava-role-menu", {
        id: this.common.id,
        menuIds: JSON.stringify(tree.getCheckedKeys(true))
      }, (res) => {
        sa.alert(res.msg, () => {
          this.initRoleInfo()
        })
      }, {})
    },
    reset() {
      let tree = this.$refs['menuData'];
      tree.setCheckedKeys([]);
      this.userData = [];
      this.userPage.total = 0;
      this.f5()
    },
    resetChecked() {
      let tree = this.$refs['menuData'];
      tree.setCheckedKeys([]);
    },
    setAllFold() { // 折叠所有节点
      sa.setItem(expandTag, false)
      this.expandAll= false
      let tree = this.$refs['menuData'];
      for (let i = 0; i < tree.store._getAllNodes().length; i++) {
        tree.store._getAllNodes()[i].expanded = false;
      }
    },
    setAllExpand() { // 展开所有节点
      sa.setItem(expandTag, true)
      this.expandAll= true
      let tree = this.$refs['menuData'];
      for (let i = 0; i < tree.store._getAllNodes().length; i++) {
        tree.store._getAllNodes()[i].expanded = true;
      }
    },
    selectionChange(s, row) {
      this.common.roleName = row.name
      this.common.id = row.id
      this.initRoleInfo()
    },
    currentChange(row, oldRow) {
      if (!row) return
      this.common.roleName = row.name
      this.common.id = row.id
      this.initRoleInfo()
    },
    initRoleInfo() { // 加载对应角色的菜单以及用户信息
      let tree = this.$refs['menuData'];
      sa.ajax(PATH + "/init-role-info", {id: this.common.id}, (res) => {

        tree.setCheckedKeys(res.data.menuIds);
        this.userF5();
      }, {type: 'get', msg: null})
    },
    deleteRow(index, rows) {
      sa.ajax(PATH + "/del", {id: index}, (res) => {
        sa.alert(res.msg, () => {
          this.f5();
        })
      }, {type: 'get', msg: null})
    },
    delAll() {
      let selects = this.$refs['roleTable'].selection
      if (selects.length === 0) return sa.error('请至少勾选一条数据')
      sa.confirm("确认删除" + sels.length + "个角色数据？删除后可能会造成拥有此角色的用户无法登录，请确认！", () => {
        sa.ajax(PATH + "/del", {ids: JSON.stringify(selects.map((i) => i.id))}, (res) => {
          sa.alert(res.msg, () => {
            this.f5();
          })
        }, {type: 'get', msg: null})
      })
    },
    userOpen() {
      sa.ajax(PATH + "/user-list", {}, (res) => {
        this.transferData = res.data
        this.value = this.userData.map(i => i.id)
      }, {msg: null, type: 'get'})
    },
    onOpen() {
    },
    onClose() {
      this.$refs['elForm'].resetFields()
    },
    close() {
      this.dialogVisible = false
    },
    handelConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        sa.ajax(PATH + "/save-or-update", this.formData, (res) => {
          sa.alert(res.msg, () => {
            this.f5();
            this.close()
          })
        }, {})
      })
    },
    showMenu(id) {
      sa.ajax(PATH + '/get-menu', {id: id}, (res) => {
        this.showMenuData = res.data
      }, {type: 'get', msg: null})
    },
    showUser(id) {
      sa.ajax(PATH + '/get-user', {id: id}, (res) => {
        this.showUserData = res.data
      }, {type: 'get', msg: null})
    },
    show(id) {
      sa.ajax(PATH + '/get', {id: id}, (res) => {
        this.showData = res.data
      }, {type: 'get', msg: null})
    },
    edit(id) {
      this.dialogTitle = '编辑角色'
      this.dialogVisible = true
      sa.ajax(PATH + '/get', {id: id}, (res) => {
        this.formData = res.data
      }, {msg: null, type: 'get'})
    },
    del(id) {
    },
    f5() {
      sa.ajax(PATH + '/list', this.rolePage, (res) => {
        let data = res.data;
        this.roleData = data.roleData.data;
        this.rolePage.total = data.roleData.dataCount;
        this.menuData = data.menuData;
      }, {type: 'get'})
      this.common = {
        id: '',
        roleName: ''
      }
    }
  },
  mounted() {

  },
  created() {
    this.f5()
  }
}
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
